// 日志记录器 - 用于调试扩展
class Logger {
  constructor() {
    this.logs = []
    this.maxLogs = 1000
    this.enabled = true
  }

  log(...args) {
    if (!this.enabled) return
    
    const timestamp = new Date().toISOString()
    const message = args.map(arg => 
      typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
    ).join(' ')
    
    const logEntry = `[${timestamp}] ${message}`
    this.logs.push(logEntry)
    
    // 限制日志数量
    if (this.logs.length > this.maxLogs) {
      this.logs.shift()
    }
    
    // 同时输出到控制台
    console.log(...args)
    
    // 保存到chrome.storage.local
    this.saveLogs()
  }

  error(...args) {
    if (!this.enabled) return
    
    const timestamp = new Date().toISOString()
    const message = args.map(arg => 
      typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
    ).join(' ')
    
    const logEntry = `[${timestamp}] ERROR: ${message}`
    this.logs.push(logEntry)
    
    if (this.logs.length > this.maxLogs) {
      this.logs.shift()
    }
    
    console.error(...args)
    this.saveLogs()
  }

  warn(...args) {
    if (!this.enabled) return
    
    const timestamp = new Date().toISOString()
    const message = args.map(arg => 
      typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
    ).join(' ')
    
    const logEntry = `[${timestamp}] WARN: ${message}`
    this.logs.push(logEntry)
    
    if (this.logs.length > this.maxLogs) {
      this.logs.shift()
    }
    
    console.warn(...args)
    this.saveLogs()
  }

  async saveLogs() {
    try {
      await chrome.storage.local.set({ 
        'wechatsync_logs': this.logs,
        'wechatsync_last_log_time': Date.now()
      })
    } catch (error) {
      console.error('保存日志失败:', error)
    }
  }

  async getLogs() {
    try {
      const result = await chrome.storage.local.get(['wechatsync_logs'])
      return result.wechatsync_logs || []
    } catch (error) {
      console.error('获取日志失败:', error)
      return []
    }
  }

  async clearLogs() {
    this.logs = []
    try {
      await chrome.storage.local.remove(['wechatsync_logs', 'wechatsync_last_log_time'])
    } catch (error) {
      console.error('清除日志失败:', error)
    }
  }

  downloadLogs() {
    const logContent = this.logs.join('\n')
    const blob = new Blob([logContent], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `wechatsync_debug_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.log`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  enable() {
    this.enabled = true
  }

  disable() {
    this.enabled = false
  }
}

// 创建全局日志实例
const logger = new Logger()

// 导出给其他地方使用
export { logger }